

package com.kimo.shop.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.kimo.shop.bean.param.UserUpdateParam;
import com.kimo.shop.common.annotation.SysLog;
import com.kimo.shop.common.config.Constant;
import com.kimo.shop.common.exception.KimoShopBindException;
import com.kimo.shop.common.util.PageParam;
import com.kimo.shop.user.comment.dto.UserTagDto;
import com.kimo.shop.user.comment.model.UserTag;
import com.kimo.shop.user.comment.model.UserTagUser;
import com.kimo.shop.user.comment.service.UserTagService;
import com.kimo.shop.user.comment.service.UserTagUserService;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;


/**
 * 客户标签
 *
 * @author kimo-taozhouchuan
 * @date 2020-09-09 11:31:16
 */
@RestController
@AllArgsConstructor
@RequestMapping("/user/userTag")
public class UserTagController {

    private final UserTagService userTagService;
    private final UserTagUserService userTagUserService;

    /**
     * 分页查询
     *
     * @param page    分页对象
     * @return 分页数据
     */
    @GetMapping("/page")
    public ResponseEntity<IPage<UserTag>> getUserTagPage(PageParam<UserTag> page) {
        return ResponseEntity.ok(userTagService.page(page, new LambdaQueryWrapper<>()));
    }

    /**
     * 通过id查询客户标签
     *
     * @param userTagId id
     * @return 单个数据
     */
    @GetMapping("/info/{userTagId}")
    public ResponseEntity<UserTag> getById(@PathVariable("userTagId") Long userTagId) {
        return ResponseEntity.ok(userTagService.getById(userTagId));
    }

    /**
     * 新增客户标签
     *
     * @param userTagDto 客户标签
     * @return 是否新增成功
     */
    @SysLog("新增客户标签")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('user:userTag:save')")
    public ResponseEntity<Boolean> save(@RequestBody @Validated(UserTagDto.AddUserTag.class) UserTagDto userTagDto) {
        int count = userTagService.count(new LambdaQueryWrapper<UserTag>().eq(UserTag::getTagType, 1));
        if(Objects.equals(userTagDto.getTagType(),1) && count + 1 > Constant.TAG_LIMIT_NUM){
            // 数量超过上限
            throw new KimoShopBindException("kimo.tag.num.check");
        }
        int nameCount = userTagService.count(new LambdaQueryWrapper<UserTag>().eq(UserTag::getTagName,userTagDto.getTagName()));
        if(nameCount > 0){
            // 标签名称已存在！
            throw new KimoShopBindException("kimo.tag.name.exist");
        }
        return ResponseEntity.ok(userTagService.addUserTag(userTagDto));
    }

    /**
     * 修改客户标签
     *
     * @param userTagDto 客户标签
     * @return 是否修改成功
     */
    @SysLog("修改客户标签")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('user:userTag:update')")
    public ResponseEntity<Boolean> updateById(@RequestBody @Validated(UserTagDto.UpdateUserTag.class) UserTagDto userTagDto) {
        int nameCount = userTagService.count(new LambdaQueryWrapper<UserTag>().eq(UserTag::getTagName,userTagDto.getTagName())
                .ne(UserTag::getUserTagId,userTagDto.getUserTagId()));
        if(nameCount > 0){
            // 标签名称已存在！
            throw new KimoShopBindException("kimo.tag.name.exist");
        }
        return ResponseEntity.ok(userTagService.updateUserTag(userTagDto));
    }

    /**
     * 通过id删除客户标签
     *
     * @param userTagId id
     * @return 是否删除成功
     */
    @SysLog("删除客户标签")
    @DeleteMapping("/{userTagId}")
    @PreAuthorize("@pms.hasPermission('user:userTag:delete')")
    public ResponseEntity<Boolean> removeById(@PathVariable Long userTagId) {
        return ResponseEntity.ok(userTagService.removeUserTag(userTagId));
    }

    /**
     * 通过id刷新客户标签统计数据
     *
     * @param userTagId id
     * @return 单个数据
     */
    @SysLog("刷新客户标签统计数据")
    @GetMapping("/refresh/{userTagId}")
    //@PreAuthorize("@pms.hasPermission('user:userTag:refresh')")
    public ResponseEntity<UserTag> refreshUserTag(@PathVariable("userTagId") Long userTagId) {
        return ResponseEntity.ok(userTagService.refreshConditionTag(userTagId));
    }

    /**
     * 可以添加的标签列表
     * @return 单个数据
     */
    @GetMapping("/getTagList" )
    public ResponseEntity<List<UserTag>> getTagList() {
        return ResponseEntity.ok(userTagService.list(null));
    }

    /**
     * 通过消息id推送给对应标签的用户
     * @param templateId id
     * @return 是否修改成功
     */
    @SysLog("状态变更" )
    @DeleteMapping("/sendMsg/{templateId}" )
    @PreAuthorize("@pms.hasPermission('admin:notifyTemplate:update')" )
    public ResponseEntity<Void> sendMsg(@PathVariable Long templateId) {
        userTagService.sendTagMsg(templateId);
        return ResponseEntity.ok().build();
    }

    /**
     * 获取手动标签
     */
    @GetMapping("/byTagType")
    public ResponseEntity<IPage<UserTag>> getTagPage(PageParam<UserTag> page, UserTag userTag) {
        PageParam<UserTag> resPage = userTagService.page(page, new LambdaQueryWrapper<UserTag>()
                .eq(userTag.getTagType() != null,UserTag::getTagType, userTag.getTagType())
                .like(StrUtil.isNotBlank(userTag.getTagName()), UserTag::getTagName, userTag.getTagName())
                .orderByDesc(UserTag::getCreateTime)
        );
        return ResponseEntity.ok(resPage);
    }

    /**
     * 平台批量修改会员标签
     */
    @PutMapping("/updateUserTag")
    public ResponseEntity<Boolean> batchUpdateUserTag(@RequestBody UserUpdateParam param) {
        return ResponseEntity.ok(userTagService.batchUpdateUserTag(param));
    }

    /**
     * 删除会员的某个标签
     */
    @DeleteMapping("/deleteUserTag")
    public ResponseEntity<Boolean> deleteUserTag(@RequestBody UserTagUser tagUser) {
        return ResponseEntity.ok(userTagUserService.removeByUserIdAndTagId(tagUser.getUserId(),tagUser.getUserTagId()));
    }
}
